package com.zpark.humpro.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

public class Md5 {



    //指定MD5加密类
    private static MessageDigest messageDigest;

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private Md5(){
        throw new AssertionError("No com.zpark.score.utils.Md5 instance for you!");

    }


    /**
     * //加密
     * @param password  用户传来的密码
     * @return MD5加密后的密码
     */

    public static String encrypt(String password){
        Objects.requireNonNull(password);
        //生成12位的随机盐
        byte[] salt = new byte[12];
        new SecureRandom().nextBytes(salt);
        //把盐拿去加密
        messageDigest.update(salt);
        //把密码拿去加密
        byte[] bytes = password.getBytes();
        messageDigest.update(bytes);
        //得到加密盐和加密密码的组合
        byte[] digest = messageDigest.digest();
        //拼接12位的加密盐到加密组合里
        byte[] encryptbytes = new byte[12 + digest.length];
        System.arraycopy(salt,0,encryptbytes,0,12);
        System.arraycopy(digest,0,encryptbytes,12,digest.length);

        return Base64.getEncoder().encodeToString(encryptbytes);
    }

    public static void main(String[] args) {
        String e1 = encrypt("123");
        String e2 = encrypt("123");

        System.out.println(e1);
        System.out.println(e2);

    }




    /**
     * 密码校验
     * @param password  用户要验证的明文登录密码
     * @param encrypt   数据库查出来的要对比的加密密码
     * @return      密码是否匹配成功
     */

    public static boolean validate(String password,String encrypt){
        //非空检查
        Objects.requireNonNull(password);
        Objects.requireNonNull(encrypt);

        //去除前12位随机盐
        byte[] decode = Base64.getDecoder().decode(encrypt);
        byte[] salt = Arrays.copyOf(decode, 12);
        //取出后面的加密盐和加密密码的组合
        byte[] bytes = Arrays.copyOfRange(decode, 12, decode.length);
        //加密盐
        messageDigest.update(salt);
        //加密密码
        messageDigest.update(password.getBytes());
        //得到加密盐和密码的组合
        byte[] digest = messageDigest.digest();
        //对比
        return Arrays.equals(bytes,digest);

    }

}
